﻿using System;
using System.IO;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Com.CodePlex.SPC3.ProfileImageUpload {

	public class UploadArgs {
		public string SiteUrl;
		public string Username;
		public string Password;
		public string SourceDirectory;
		public string FilenameFormat;
		public string AuthType;
	}

	public class ManagerResult {
		public bool Success = false;
	}

	public class ProfileImageUploadManager {

		SharePointDAO sharepointdao = new SharePointDAO();

		public ManagerResult Validate(UploadArgs args, BackgroundWorker worker) {
			ManagerResult result = new ManagerResult();
			worker.ReportProgress(0, "Validating inputs");
			worker.ReportProgress(0, "Connecting to site");
			DAOResult daoresult = sharepointdao.ConnectToSite(args.SiteUrl, args.Username, args.Password, args.AuthType);
			if (daoresult.Success) {
				result.Success = true;
			} else {
				worker.ReportProgress(0, new WorkerMessage("Cannot connect to site", System.Drawing.Color.Red));
				worker.ReportProgress(0, new WorkerMessage(daoresult.Message, System.Drawing.Color.Red));
			}
			return result;
		}

		public ManagerResult Process(UploadArgs args, BackgroundWorker worker) {
			ManagerResult result = new ManagerResult();
			result.Success = true;
			worker.ReportProgress(0, "Processing");
			worker.ReportProgress(0, "Files to upload: " + Directory.GetFiles(args.SourceDirectory).Length);
			foreach (string filename in Directory.GetFiles(args.SourceDirectory)) {
				worker.ReportProgress(0, filename);

				string name = Path.GetFileNameWithoutExtension(filename) + "_LThumb" + Path.GetExtension(filename);
				worker.ReportProgress(0, "resizing 144x144");
				byte[] data;
				try {
					data = Ext.ResizeImage(filename, 144, 144);
				} catch (ArgumentException ex) {
					worker.ReportProgress(0, new WorkerMessage("Invalid image.", System.Drawing.Color.Red));
					continue;
				}
				worker.ReportProgress(0, "uploading 144x144");
				string url = null;
				try {
					url = sharepointdao.UploadDocument(args.SiteUrl, args.Username, args.Password, args.AuthType, "User Photos", "Profile Pictures", name, data);
				} catch (Microsoft.SharePoint.Client.ServerUnauthorizedAccessException ex) {
					worker.ReportProgress(0, new WorkerMessage("Username and password supplied does not have permission to modify profiles.", System.Drawing.Color.Red));
					result.Success = false;
					break;
				}
				worker.ReportProgress(0, "uploaded: " + url);

				name = Path.GetFileNameWithoutExtension(filename) + "_MThumb" + Path.GetExtension(filename);
				worker.ReportProgress(0, "resizing 96x96");
				data = Ext.ResizeImage(filename, 96, 96);
				worker.ReportProgress(0, "uploading 96x96");
				url = sharepointdao.UploadDocument(args.SiteUrl, args.Username, args.Password, args.AuthType, "User Photos", "Profile Pictures", name, data);
				string pictureurl = url;
				worker.ReportProgress(0, "uploaded: " + url);

				name = Path.GetFileNameWithoutExtension(filename) + "_SThumb" + Path.GetExtension(filename);
				worker.ReportProgress(0, "resizing 32x32");
				data = Ext.ResizeImage(filename, 32, 32);
				worker.ReportProgress(0, "uploading 32x32");
				url = sharepointdao.UploadDocument(args.SiteUrl, args.Username, args.Password, args.AuthType, "User Photos", "Profile Pictures", name, data);
				worker.ReportProgress(0, "uploaded: " + url);

				Match match = Regex.Match(Path.GetFileNameWithoutExtension(filename), args.FilenameFormat);
				string accountname = match.Groups[1].Value + @"\" + match.Groups[2].Value;
				string value = sharepointdao.SelectProfileProperty(args.SiteUrl, args.Username, args.Password, args.AuthType, accountname, "PictureURL");
				if (value != pictureurl) {
					if (value == null) {
						worker.ReportProgress(0, "creating PictureURL");
					} else {
						worker.ReportProgress(0, "updating PictureURL");
						worker.ReportProgress(0, "old PictureURL: " + value);
					}
					try {
						sharepointdao.UpdateProfileProperty(args.SiteUrl, args.Username, args.Password, args.AuthType, accountname, "PictureURL", pictureurl);
					} catch (Exception ex) {
						worker.ReportProgress(0, new WorkerMessage("Failed to modify profile property.", System.Drawing.Color.Red));
						worker.ReportProgress(0, new WorkerMessage(ex.ToString(), System.Drawing.Color.Red));
						result.Success = false;
						break;
					}
					value = sharepointdao.SelectProfileProperty(args.SiteUrl, args.Username, args.Password, args.AuthType, accountname, "PictureURL");
					worker.ReportProgress(0, "new PictureURL: " + value);
				}
			}

			return result;
		}
	}
}
